#!/usr/bin/env python
# coding=utf-8
# @FileName :hooks.py
# @Time     :2022/2/10 16:28
# @Author   :ZXC
# @Desc     :
import datetime
import uuid
from typing import Any

from jsonpath import jsonpath
from loguru import logger

from config.settings import extra_pool


def get_current_highest(delta_days: int = 0):
    """
    获取时间戳(毫秒)
    支持加减天数
    :param delta_days: 整数，正数表示后几天，负数表示前几天
    :return:
    """
    current = int(float((datetime.datetime.now() + datetime.timedelta(delta_days)).timestamp())) * 1000

    return current


def create_uuid(num):
    """
    生成uuid
    :param num: 一个标记，防止一个替换存在多个时出现冲突
    :return:
    """
    return uuid.uuid4()


"""
数据库操作方法
"""


def exec_mysql(sql: str, to_extra_pool: bool = True) -> str:
    """
    MYSQL执行
    :param sql:
    :param to_extra_pool: 是否写入变量池
    :return:
    """
    from tools.db_client import mysql_client
    res = mysql_client.execute_sql(sql)
    if to_extra_pool:
        update_extra_pool('mysql', res)
    return str(res)


def exec_tidb(sql: str, to_extra_pool: bool = True) -> str:
    """
    TIDB执行
    :param sql:
    :param to_extra_pool: 是否写入变量池
    :return:
    """
    from tools.db_client import tidb_client
    res = tidb_client.execute_sql(sql)
    if to_extra_pool:
        update_extra_pool('tidb', res)
    return str(res)


"""
变量池操作方法
"""


def get_extra_pool_by_jsonpath(expr: str = '.') -> Any:
    """
    从变量池获取数据(在断言处用的比较多)
    :param expr: jsonpath表达式。使用时需要将$缓存大写的V
    :return:
    """
    result = None
    try:
        expr = '$' + expr.lstrip('V')
        result = jsonpath(extra_pool, expr)[0]
    except Exception as e:
        logger.warning(f'从变量池获取数据失败：{expr}\n{e}')
    logger.info(f'从变量池获取数据完成，提取结果为===>{result}')
    return result


def update_extra_pool(key, value):
    """
    更新参数池
    :param key: 键
    :param value: 值
    :return:
    """

    extra_pool[key] = value
    return extra_pool


def update_organ_by_organ_name(organ_name):
    """
    根据机构名称更新变量池的（单个）机构信息
    :param organ_name:
    :return: 机构信息
    """
    organ_tree = extra_pool.get('organ_tree')
    organ = jsonpath(organ_tree, f'$..[?(@.organName=="{organ_name}")]')[0]
    extra_pool.update({
        "organ": organ
    })
    return organ


if __name__ == '__main__':
    print(get_current_highest(-1))
